package me.zingon.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import me.zingon.cache.UserCache;
import me.zingon.common.Code;
import me.zingon.common.Constant;
import me.zingon.service.EmailService;
import org.apache.http.client.ClientProtocolException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;

import me.zingon.model.User;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
@Scope("session")
@RequestMapping("/user")
public class UserController {
	@Autowired
	UserCache userCache;



	@Autowired
	Properties msg;

	// @RequestMapping("/getCode.ztc")
 //    @ResponseBody
 //    public Object getCode() throws Exception {
 //        Map<String,String> result= new HashMap<String,String>(1);
 //        result.put("code", userCache.getCode());
 //        return result;
 //    }
	
	@RequestMapping("/getUsers.ztc")
	@ResponseBody
	public Object getUsers(){ 
		return userCache.getUsers();
	}


    @RequestMapping("/login.*")
    public ModelAndView login(@RequestParam("email")String email,
                              @RequestParam("rinpsipd")String rinpsipd,
                              HttpServletRequest req,
                              ModelAndView model){
        User u=new User();
        u.setEmail(email);
        u.setRinpsipd(rinpsipd);
        User du=userCache.login(u);
        if(du!=null){
			req.getSession().setAttribute(Constant.SESSION_USER, du);
			req.getSession().setAttribute(Constant.SESSION_TRAD, userCache.getTrad(du.getTradId()));
			req.getSession().setAttribute(Constant.SESSION_CLAZZ, userCache.getClazz(du.getClassId()));
			if(du.isActivedFlag()) {
				model.setViewName("redirect:/materials" + (req.getSession().getAttribute(Constant.SESSION_STYLE) == null ? ".pj" : req.getSession().getAttribute(Constant.SESSION_STYLE)));
			}else{
				model.setViewName("/login");
				model.addObject("msg", Code.ActiveUser.getCode());
			}
			return model;
		}
		model.setViewName("/login");
        model.addObject("msg", Code.LoginError.getCode());
        return model;
    }

    @RequestMapping("/register.*")
    public String register(@RequestParam("nickname")String nickname,
						   @RequestParam("email")String email,
						   @RequestParam("rinpsipd")String rinpsipd,
						   @RequestParam(value = "qq",required = false,defaultValue = "0")String qq,
						   @RequestParam(value = "weixin",required = false,defaultValue = "0")String weixin,
						   @RequestParam(value = "phone",required = false,defaultValue = "00000000000")String phone,
						   HttpServletRequest req,
						   RedirectAttributes model){
        User u= (User) req.getSession().getAttribute(Constant.SESSION_USER);
        if(u==null)
            return "/error";
        u.setNickname(nickname);
        u.setEmail(email);
        u.setRinpsipd(rinpsipd);
        u.setQq(qq);
        u.setWeixin(weixin);
        u.setPhone(phone);
		userCache.register(u);
		userCache.sendActiveEmail(req,u);
		model.addFlashAttribute("msg",Code.RegisterSuccess.getCode());
        return "redirect:/user"+(req.getSession().getAttribute(Constant.SESSION_STYLE)==null?".pj":req.getSession().getAttribute(Constant.SESSION_STYLE));
    }


	@RequestMapping("/send.ztc")
	@ResponseBody
	public Object sendActiveEmail(@RequestParam("email")String email,
								  HttpServletRequest req){
		User u = (User) req.getSession().getAttribute(Constant.SESSION_USER);
		if(!email.equals("")) {
			User user=new User();
			user.setId(u.getId());
			user.setEmail(email);
			u.setEmail(email);
			userCache.register(user);
			req.getSession().removeAttribute(Constant.SESSION_USER);
			req.getSession().removeAttribute(Constant.SESSION_CLAZZ);
			req.getSession().removeAttribute(Constant.SESSION_TRAD);
		}
		Map<String,String> result= new HashMap<>(1);
		if(u!=null && u.getEmail()!=null){
			userCache.sendActiveEmail(req,u);
			result.put("result","success");
		}else
			result.put("result","error");
		return result;
	}


	/**
	 * 激活接口.
	 * 用于已注册用户的激活
	 */
	@RequestMapping("/active/{email}/{uuid}")
	public String activeUser(@PathVariable("email")String email,
							 @PathVariable("uuid")String uuid,
							 HttpServletRequest req,
							 RedirectAttributes model) throws UnsupportedEncodingException {
		userCache.activeUser(email,uuid);
		model.addFlashAttribute("msg",Code.ActiveSuccess.getCode());
		return "redirect:/user"+(req.getSession().getAttribute("style")==null?".pj":req.getSession().getAttribute("style"));
	}

	/**
	 * 验证借口.
	 * 验证是否是通大学生
	 * @param xh
	 * @param sfzh
	 * @param pwd
	 * @param yzm
	 * @param req
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	@RequestMapping("/testUser.ztc")
    @ResponseBody
	public Object testUser(@RequestParam("xh")String xh,
						   @RequestParam("sfzh")String sfzh,
						   @RequestParam("pwd")String pwd,
						   @RequestParam("yzm")String yzm,
						   HttpServletRequest req,
						   ModelAndView model) throws IOException{
        Map<String,String> result=new HashMap<String, String>(1);
		String ip=req.getRemoteAddr();
		User user= userCache.testUser(xh, sfzh, pwd, yzm,ip);
		if(user!=null){
			//是学生
			req.getSession().setAttribute(Constant.SESSION_USER,user );
			req.getSession().setAttribute(Constant.SESSION_TRAD, userCache.getTrad(user.getTradId()));
			req.getSession().setAttribute(Constant.SESSION_CLAZZ, userCache.getClazz(user.getClassId()));
            if(user.getNickname()==null)
				result.put("result", Code.UserSuccess.getCode());
			else
                result.put("result", Code.UserExist.getCode());
            return result;
		} 
		result.put("result",Code.UserError.getCode());
		return result;
	}


	
	@RequestMapping("/getYzm.ztc")
	public void myGet(HttpServletResponse res) throws Exception {
		userCache.getYzm(res);
	}

	@RequestMapping("/changeStyle")
	public String changeStyle(HttpServletRequest req){
		if(".pj".equals(req.getSession().getAttribute("style"))){
			req.getSession().setAttribute(Constant.SESSION_STYLE, ".ztc");
		}else{
			req.getSession().setAttribute(Constant.SESSION_STYLE, ".pj");
		} 
		return "redirect:/view"+req.getSession().getAttribute(Constant.SESSION_STYLE);
	}
}
